package com.icss.ah.orderFee.service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.icss.ah.base.bean.EasyuiDataGridJson;
import com.icss.ah.base.util.DateUtils;
import com.icss.ah.base.util.ResourceLoader;
import com.icss.ah.util.HttpUtil;

@Service
public class OrderFeeService {
	
	private final Logger errlog = Logger.getLogger("E");
	private final Logger infolog = Logger.getLogger("I");
	//提现接口服务
	private String payServiceUrl = ResourceLoader.getInstance("icss").getString("payServiceUrl");
	
	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;
	private EasyuiDataGridJson dataGridJson = new EasyuiDataGridJson();
	
	DecimalFormat format = new DecimalFormat("0.00");
	/**
	 * 检查历史提现订单状态
	 * @param map
	 * @return
	 */
	public String checkAgentPayOrders(HashMap map){
		String result = "0, ";
		try {
			//获取待检查列表
			List orderList = sqlSessionTemplate.selectList("OrderFeeBean.queryAgentPayOrdersCheck", map);
			if(orderList!=null&&!orderList.isEmpty()){
				for(Iterator<HashMap> i = orderList.iterator();i.hasNext();){
					HashMap order = i.next();
					HashMap query = new HashMap();
					query.put("mchCode", order.get("MCH_CODE"));
					query.put("shopId", order.get("SHOP_ID"));
					query.put("queryType", "07");
					query.put("orderNo", order.get("ORDER_NO"));
					query.put("queryOrderNo", order.get("PAY_ID"));
					checkAgentPayOrderDeal(query);
				}
			}
		} catch (Exception e) {
			errlog.error("OrderFeeService|checkAgentPayOrders|异常：",e);
		}
		return result;
	}
	/**
	 * 提现订单查询处理
	 * @param query
	 * @return
	 */
	public String checkAgentPayOrderDeal(HashMap query){
		String result = "0, ";
		try {
			JSONObject dataJson = JSONObject.fromObject(query);
			//记录日志
			infolog.info("OrderFeeService|checkAgentPayOrderDeal|dataJson:"+dataJson.toString());
			String httpUrl = payServiceUrl+"/gomePay/queryOrderDealResult.do";
			//记录日志
			infolog.info("OrderFeeService|checkAgentPayOrderDeal|httpUrl:"+httpUrl);
			JSONObject resultJson = HttpUtil.connectHttp(httpUrl, dataJson.toString(), "utf-8");
			//记录日志
			infolog.info("OrderFeeService|checkAgentPayOrderDeal|resultJson:"+resultJson.toString());
			boolean opeFlag= resultJson.getBoolean("success");
			if(opeFlag){
				JSONObject reObj = resultJson.getJSONObject("obj");
				String resultCode = reObj.getString("RESULT_CODE");
				if("000".equals(resultCode)){
					HashMap reMap = (HashMap)JSONObject.toBean(reObj, HashMap.class);
					String PAY_STATUS = "";
					if(reObj.containsKey("PAY_STATUS")){
						PAY_STATUS = reObj.getString("PAY_STATUS");
					} else {
						PAY_STATUS = "3";
						reMap.put("PAY_STATUS", PAY_STATUS);
					}
					if("1".equals(PAY_STATUS)||"2".equals(PAY_STATUS)){
						reMap.put("PAY_CHECK", "1");
					}
					//记录日志
					infolog.info("OrderFeeService|checkAgentPayOrderDeal|updateAgentPayStatus|reMap:"+reMap);
					sqlSessionTemplate.update("OrderFeeBean.updateAgentPayStatus", reMap);
					if("1".equals(PAY_STATUS)||"3".equals(PAY_STATUS)){
						query.put("LAST_TIMESTAMP", DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
						query.put("agentStatus", PAY_STATUS);
						query.put("remark", "提现操作成功");
						//记录日志
						infolog.info("OrderFeeService|agentPay|updateAgentOrderStatus|map:"+query);
						sqlSessionTemplate.update("OrderFeeBean.updateAgentOrderStatus", query);
						result = "1,提现操作成功,请稍后查询结果";
					} else {
						result = "2,提现操作失败";
					}
				} else {
					result = "2,提现服务异常，请稍后再试";
				}
			} else{
				result = "2,提现异常，请稍后再试";
			}
		} catch (Exception e) {
			errlog.error("OrderFeeService|checkAgentPayOrderDeal|异常：",e);
		}
		return result;
	}
	public EasyuiDataGridJson queryFeeList(HashMap<String, String> map){
		try {
			List<Map<String, Object>> rows = sqlSessionTemplate.selectList("OrderFeeBean.queryFeeList",map);
			Long total = sqlSessionTemplate.selectOne("OrderFeeBean.queryFeeListCount",map);
			Map<String, Object> obj = sqlSessionTemplate.selectOne("OrderFeeBean.queryActualAmount",map);
			if(rows != null && rows.size() > 0){
				rows.get(0).put("actualAmount", obj.get("ACTUALAMOUNT"));
				rows.get(0).put("allOrderMoney", obj.get("ORDER_MONEY"));
				rows.get(0).put("allRefundMoney", obj.get("REFUND_MONEY"));
			}
			dataGridJson.setRows(rows);
			dataGridJson.setTotal(total);
		} catch (Exception e) {
			errlog.error("OrderFeeService|queryFeeList|异常：",e);
		}
		return dataGridJson;
	}
	
	public List<Map<String, Object>> queryExportOrderFeeInfo(HashMap<String, String> map){
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try {
			list = sqlSessionTemplate.selectList("OrderFeeBean.queryExportOrderFeeInfo",map);
			infolog.info("OrderFeeService|queryExportOrderFeeInfo|list:"+list);
		} catch (Exception e) {
			errlog.error("OrderFeeService|queryExportOrderFeeInfo|异常：",e);
		}
		return list;
	}
	
	public HashMap queryActualAmount(HashMap<String, String> map){
		HashMap result = new HashMap<String, Object>();
		try {
			result= sqlSessionTemplate.selectOne("OrderFeeBean.queryActualAmount",map);
			result = result == null ? new HashMap() : result;
			if(result.isEmpty()){
				result.put("ACTUALAMOUNT", "0.00");
			}
		} catch (Exception e) {
			errlog.error("OrderFeeService|queryActualAmount|异常：",e);
		}
		return result;
	}
	/**
	 * 获取用户金额流水合计
	 * @param map
	 * @return
	 */
	public HashMap queryShopMoney(HashMap<String, String> map){
		HashMap result = new HashMap<String, Object>();
		try {
			result= sqlSessionTemplate.selectOne("OrderFeeBean.queryShopMoney",map);
			result = result == null ? new HashMap() : result;
			if(result.isEmpty()){
				result.put("ALL_BILL_MONEY", "0.00");
				result.put("ALL_REAL_MONEY", "0.00");
				result.put("ALL_AGENT_MONEY", "0.00");
			}
		} catch (Exception e) {
			errlog.error("OrderFeeService|queryActualAmount|异常：",e);
		}
		return result;
	}
	/**
	 * 获取用户已提现以及处理中金额
	 * @param map
	 * @return
	 */
	public HashMap queryUserAgentMoneyInfo(HashMap<String, String> map){
		HashMap result = new HashMap<String, Object>();
		try {
			result= sqlSessionTemplate.selectOne("OrderFeeBean.queryUserAgentMoneyInfo",map);
			result = result == null ? new HashMap() : result;
			if(result.isEmpty()){
				result.put("OVER_MONEY", "0.00");
				result.put("PAYING_MONEY", "0.00");
			}
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("OrderFeeService|queryUserAgentMoneyInfo|异常：",e);
		}
		return result;
	}
	/**
	 * 获取提现手续费
	 * @return
	 */
	public String getAgentFee(HashMap map){
		String agentFee = "";
		try {
			agentFee= sqlSessionTemplate.selectOne("OrderFeeBean.getAgentFee",map);
			agentFee = agentFee == null || agentFee.equals("") ? "0" : agentFee;
			agentFee = format.format(Double.valueOf(agentFee));
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("OrderFeeService|agentFee|异常：",e);
		}
		return agentFee;
	}

	/**
	 * 保存用户提现信息并返回订单号
	 * @param param
	 * @return
	 */
	public String saveUserAgentPayInfo(HashMap param){
		String orderNo = "";
		try {
			String curDateTimeNo = "AP"+DateUtils.getCurrentDate("yyyyMMddHHmmss");
			param.put("orderNo", curDateTimeNo);
			String curOrderNo = sqlSessionTemplate.selectOne("OrderFeeBean.queryCurAgentOrderNo", param);
			curOrderNo = curOrderNo == null ? "" : curOrderNo;
			if(curOrderNo.equals("")){
				orderNo = curDateTimeNo+"001";
			} else {
				//已有支付流水，增量生成新的支付流水
				String tempId = curOrderNo.substring(curOrderNo.length()-3, curOrderNo.length());
				tempId = Integer.parseInt(tempId)+1+"";
				tempId = "000"+tempId;
				orderNo = curDateTimeNo+tempId.substring(tempId.length()-3, tempId.length());
			}
			//记录日志
			infolog.info("OrderFeeService|saveUserAgentPayInfo|orderNo:"+orderNo);
			String orderMoney = param.get("orderMoney").toString();
			
			param.put("orderNo", orderNo);
			param.put("status", "0");
			param.put("remark", "提现订单新增");
			//新增提现订单
			sqlSessionTemplate.insert("OrderFeeBean.insertCurAgentOrderInfo", param);
			//新增提现订单-账单流水
			sqlSessionTemplate.insert("OrderFeeBean.insertCurAgentBillFlow", param);
			//记录日志
			infolog.info("OrderFeeService|saveUserAgentPayInfo|insertCurAgentOrderInfo:"+true);
		} catch (Exception e) {
			orderNo ="";
			errlog.error("OrderFeeService|saveUserAgentPayInfo|异常：",e);
		}
		return orderNo;
	}
	
	/**
	 * 执行提现操作
	 * @param map
	 * @return
	 */
	public String agentPay(HashMap map){
		String result = "0, ";
		try {
			String realMoney = sqlSessionTemplate.selectOne("OrderFeeBean.queryAgentOrderRealMoney", map);
			realMoney = realMoney == null ? "0" : realMoney;
			//记录日志
			infolog.info("OrderFeeService|agentPay|realMoney:"+realMoney);
			if(Float.parseFloat(realMoney)<=0){
				result = "2,实际到账金额不符";
			} else {
				HashMap agentInfo = new HashMap();
				agentInfo.put("mchCode", map.get("mchCode"));
				agentInfo.put("shopId", map.get("shopId"));
				agentInfo.put("sellNo", map.get("sellNo"));
				agentInfo.put("customerName", map.get("bankAccountName"));
				agentInfo.put("accountNumber", map.get("bankAccount"));
				agentInfo.put("orderMoney", realMoney);
				JSONObject dataJson = JSONObject.fromObject(agentInfo);
				//记录日志
				infolog.info("OrderFeeService|agentPay|dataJson:"+dataJson.toString());
				String httpUrl = payServiceUrl+"/agentPay/agentPay.do";
				//记录日志
				infolog.info("OrderFeeService|agentPay|httpUrl:"+httpUrl);
				JSONObject resultJson = HttpUtil.connectHttp(httpUrl, dataJson.toString(), "utf-8");
				//记录日志
				infolog.info("OrderFeeService|agentPay|resultJson:"+resultJson.toString());
				boolean opeFlag= resultJson.getBoolean("success");
				if(opeFlag){
					JSONObject reObj = resultJson.getJSONObject("obj");
					String resultCode = reObj.getString("RESULT_CODE");
					if("000".equals(resultCode)){
						HashMap reMap = (HashMap)JSONObject.toBean(reObj, HashMap.class);
						String PAY_STATUS = "";
						if(reObj.containsKey("PAY_STATUS")){
							PAY_STATUS = reObj.getString("PAY_STATUS");
						} else {
							PAY_STATUS = "3";
							reMap.put("PAY_STATUS", PAY_STATUS);
						}
						//记录日志
						infolog.info("OrderFeeService|agentPay|updateAgentPayStatus|reMap:"+reMap);
						sqlSessionTemplate.update("OrderFeeBean.updateAgentPayStatus", reMap);
						if("1".equals(PAY_STATUS)||"3".equals(PAY_STATUS)){
							map.put("LAST_TIMESTAMP", DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
							map.put("agentStatus", PAY_STATUS);
							map.put("remark", "提现操作成功");
							//记录日志
							infolog.info("OrderFeeService|agentPay|updateAgentOrderStatus|map:"+map);
							sqlSessionTemplate.update("OrderFeeBean.updateAgentOrderStatus", map);
							result = "1,提现操作成功,请稍后查询结果";
						} else {
							result = "2,提现操作失败";
						}
					} else {
						result = "2,提现服务异常，请稍后再试";
					}
				} else{
					result = "2,提现异常，请稍后再试";
				}
			}
		} catch (Exception e) {
			result = "2,"+e.getMessage();
			errlog.error("OrderFeeService|agentPay|异常：",e);
		}
		//记录日志
		infolog.info("OrderFeeService|agentPay|result:"+result);
		return result;
	}
	
	/**
	 * 代付结果查询
	 * @param map
	 * @return
	 */
	public String checkAgengOrderResult(HashMap map){
		String result = "0, ";
		try {
			HashMap order = sqlSessionTemplate.selectOne("OrderFeeBean.queryAgentOrderCheck",map);
			if(order!=null && !order.isEmpty()){
				HashMap query = new HashMap();
				query.put("mchCode", order.get("MCH_CODE"));
				query.put("queryOrderNo", order.get("PAY_ID"));
				query.put("queryType", "7");
				JSONObject dataJson = JSONObject.fromObject(query);
				//记录日志
				infolog.info("OrderFeeService|checkAgengOrderResult|dataJson:"+dataJson.toString());
				String httpUrl = payServiceUrl+"/gomePay/queryOrderDealResult.do";
				//记录日志
				infolog.info("OrderFeeService|checkAgengOrderResult|httpUrl:"+httpUrl);
				JSONObject resultJson = HttpUtil.connectHttp(httpUrl, dataJson.toString(), "utf-8");
				//记录日志
				infolog.info("OrderFeeService|checkAgengOrderResult|resultJson:"+resultJson.toString());
				boolean opeFlag= resultJson.getBoolean("success");
				if(opeFlag){
					JSONObject reObj = resultJson.getJSONObject("obj");
					String resultCode = reObj.getString("RESULT_CODE");
					if("000".equals(resultCode)){
						HashMap reMap = (HashMap)JSONObject.toBean(reObj, HashMap.class);
						String PAY_STATUS = "";
						if(reObj.containsKey("PAY_STATUS")){
							PAY_STATUS = reObj.getString("PAY_STATUS");
						} else {
							PAY_STATUS = "3";
							reMap.put("PAY_STATUS", PAY_STATUS);
						}
						//记录日志
						infolog.info("OrderFeeService|checkAgengOrderResult|updateAgentPayStatus|reMap:"+reMap);
						sqlSessionTemplate.update("OrderFeeBean.updateAgentPayStatus", reMap);
						if("1".equals(PAY_STATUS)||"3".equals(PAY_STATUS)){
							map.put("LAST_TIMESTAMP", DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
							map.put("agentStatus", PAY_STATUS);
							map.put("remark", "查询提现结果成功");
							map.put("mchCode", order.get("MCH_CODE"));
							map.put("orderNo", map.get("orderId"));
							//记录日志
							infolog.info("OrderFeeService|checkAgengOrderResult|updateAgentOrderStatus|map:"+map);
							sqlSessionTemplate.update("OrderFeeBean.updateAgentOrderStatus", map);
							sqlSessionTemplate.update("OrderFeeBean.updateAgentBillOrderResult", reMap);
							result = "1,查询提现结果成功";
						} else {
							result = "2,提现失败";
						}
					} else {
						result = "2,查询服务异常，请稍后再试";
					}
				} else{
					result = "2,查询异常，请稍后再试";
				}
			} else {
				result = "2,payInfo记录已更改";
			}
		} catch (Exception e) {
			result = "2,"+e.getMessage();
			errlog.error("OrderFeeService|checkAgengOrderResult|异常：",e);
		}
		return result;
	}
	
	public EasyuiDataGridJson queryAgentOrder(HashMap<String, String> map){
		try {
			List<Map<String, Object>> rows = sqlSessionTemplate.selectList("OrderFeeBean.queryAgentOrder",map);
			Long total = sqlSessionTemplate.selectOne("OrderFeeBean.queryAgentOrderCount",map);
			dataGridJson.setRows(rows);
			dataGridJson.setTotal(total);
		} catch (Exception e) {
			errlog.error("OrderFeeService|queryAgentOrder|异常：",e);
		}
		return dataGridJson;
	}
	
	public List<Map<String, Object>> queryExportAgentOrder(Map<String, String> map){
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try {
			list = sqlSessionTemplate.selectList("OrderFeeBean.queryExportAgentOrder",map);
			infolog.info("OrderFeeService|queryExportAgentOrder|list:"+list);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("OrderFeeService|queryExportAgentOrder|异常：",e);
		}
		return list;
	}
}
